// pages/container/goods-details/goods-details.js
const WxParse = require("../../../wxParse/wxParse.js");
const tool = require("../../../utils/util.js");
const server = require("../../../utils/server.js");
const common = require("../../../utils/common.js");
const app = getApp();
const getDataset = tool.getDataset;
var startPoint;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageShow: false,
    loginData: {},
    timer: null,
    chooseBuyMethod: 0,
    isAuthSet: false, //用户是否授权获取个人信息
    optionModelName: "",
    isShowRichText: false,
    goodsDetails: {},
    recommendGoods: [],
    companyInfo: {},
    isIPhoneX: false,
    userInfo: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function(options) {
    const _this = this;
    const dev = wx.getSystemInfoSync();
    app.getLoadData().then(function(res) {
      const userInfo = res.data;
      var showType = false;
      // 加载商品详情
      _this.loadGoodsDetails(options);
      // 加载公司信息
      _this.loadCompanyInfo();
      // 加载关联商品
      _this.loadCommonGoods(options.goodsId);
      if (options.showType === "story") {
        showType = true;
      }

      _this.setData({
        isIPhoneX: app.globalData.isIPhoneX,
        userInfo: userInfo,
        showType: showType,
        iconCartPosX: dev.windowWidth - 60,
        iconCartPosY: dev.windowHeight * 0.8
      });
      if (options.type == "share") {
        _this.setData({
          shareParam: options
        })
      }
      if (options.fromMemberId) {
        _this.setData({
          fromMemberId: options.fromMemberId
        });
      }
      // 查看为用户是否授权用户信息
      wx.getSetting({
        success: function(res) {
          if (res.authSetting['scope.userInfo']) {
            wx.getUserInfo({
              success: function(res) {
                if (res.errMsg == "getUserInfo:ok") {
                  _this.setData({
                    isAuthSet: true
                  });
                  if (res.userInfo.avatarUrl !== userInfo.member_avatar) {
                    const param = {
                      member_id: userInfo.member_id,
                      member_avatar: res.userInfo.avatarUrl
                    }
                    server.postJSON("/index/user/saveMember", param, function(res) {
                      if (res.data.error != 0) {
                        tool.warning(res.data.message);
                        return;
                      }
                    });
                  }
                }
              }
            })
          }
        }
      });
    })
  },
  // 设置拼团 成员头像
  getShareMemberInfo: function(options) {
    let memberAvatarList = [];
    const _this = this;
    if (options.type == "share") {
      const shareParam = {
        cantuanid: options.cantuanid
      }
      let memberAvatarList = _this.data.memberAvatarList;
      server.postJSON("/index/chat/groupInfo", shareParam, function(res) {
        if (res.data.error != 0) {
          tool.warning(res.data.message);
          return;
        }
        for (var i = 0; i < res.data.data.data.length; i++) {
          memberAvatarList[i] = res.data.data.data[i];
        }

        _this.setData({
          memberAvatarList: memberAvatarList
        })
      });
    }
  },
  // 显示聊天界面
  showChat: function() {
    const _this = this;
    if (!app.isMember(_this.data.userInfo)) {
      _this.setData({
        showLoginType: 'showChat'
      });
      _this.loginView.showModel();
      return;
    }
    const param = {
      getMsgType: "goods",
      goods_label: _this.data.goodsDetails.goods_label,
      member_id: app.globalData.userInfo.member_id,
      ser_id: _this.data.serverData.ser_id,
      goods_id: this.data.goodsDetails.goods_id
    }
    server.postJSON("/index/chat/selectmsg", param, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      for (var i = 0; i < res.data.data.data.length; i++) {
        res.data.data.data[i].send_time = tool.formatDate(new Date(res.data.data.data[i].add_time * 1000), 'mm-dd hh:ii:ss')
      }
      _this.setData({
        msgData: res.data.data
      })
      _this.chat.showModal();
    })
  },
  _resetMsg: function() {
    this.showChat()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //获取聊天组件
    this.chat = this.selectComponent("#chat");
    //获得登陆组件
    this.loginView = this.selectComponent("#login-view");
    // 获取选择参数组件
    this.goodsParamDialog = this.selectComponent("#goods-param-dialog");

  },


  /**
   * 点击规格选项
   */
  _changeSpec(options) {
    const _this = this;
    const goodsDetails = _this.data.goodsDetails;
    const defaultSpecIndex = tool.getComponentDetail(options).defaultSpecIndex;
    let spec = goodsDetails.spec;
    //查找当前点击规格的库存 如果为0 则不重新设置
    if (spec[defaultSpecIndex].goods_storage && spec[defaultSpecIndex].goods_storage > 0) {
      this.setData({
        "goodsDetails.defaultSpecIndex": defaultSpecIndex
      })
      _this._setSelectedPrice();
    }
    // 如果是月定制重置 月份数量为0
    if (_this.data.chooseBuyMethod == 1) {
      _this._getSerializeMonth();
    }
  },
  // 判断使用哪个价格
  _setSelectedPrice: function() {
    const _this = this;
    const goodsDetails = _this.data.goodsDetails;
    const defaultSpecIndex = goodsDetails.defaultSpecIndex;
    let spec = goodsDetails.spec;
    let selectedPrice;
    switch (_this.data.chooseBuyMethod) {
      case 0:
        selectedPrice = spec[defaultSpecIndex].goods_price;
        break;
      case 1:
        selectedPrice = spec[defaultSpecIndex].goods_mon_price;
        break;
      case 2:
        selectedPrice = spec[defaultSpecIndex].goods_group_price;
        break;
      case 3:
        selectedPrice = spec[defaultSpecIndex].goods_crowd_price;
        break;
    }
    _this.setData({
      "goodsDetails.selectedPrice": selectedPrice
    })
  },
  //月定制计算月份
  _getSerializeMonth: function() {
    const _this = this;
    var _date = [],
      dateData = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    //准备一个月份反转的数组
    var dateDataRet = Object.assign([], dateData).reverse();
    //获取当前年份
    var yearText = new Date().getFullYear();
    //获取当前月份  调试的时候，大家可以通过调整now调试  3月-now=2,12月now=11...
    var nowDate = (new Date()).getDate();
    // var nowMonth = 11;
    var nowMonth = new Date().getMonth() - 1;
    var startMonth = nowMonth;
    if (_this.data.goodsDetails.delivery_time <= nowDate) {
      if (nowMonth == 11) {
        startMonth = 0;
      } else {
        startMonth = nowMonth + 1;
      }
    }
    for (let i = 0; i < 12; i++) {
      if (startMonth - i < 0) {
        //如果startMonth-i<0，从dateDataRet里面拿数据，下标=|startMonth-i|-1。
        _date.push({
          year: yearText,
          month: dateDataRet[Math.abs(startMonth - i) - 1],
          count: 0
        });
      } else {
        //从dateData里面拿数据，下标=startMonth-i
        _date.push({
          year: yearText + 1,
          month: dateData[startMonth - i],
          count: 0
        });
      }
    }
    _date.reverse();
    _this.setData({
      "goodsDetails.serializeMonth": _date
    })
  },
  /**
   * 显示普通商品富文本
   */
  showRichText: function() {
    const _this = this;
    _this.setData({
      isShowRichText: !_this.data.isShowRichText
    })
  },
  loadCommonGoods: function(id) {
    var _this = this;
    server.postJSON("/index/goods/goods_common", {
      goods_id: id
    }, function(res) {
      if (res.data.error !== 0) {
        tool.warning(res.data.message);
        return;
      }
      _this.setData({
        recommendGoods: res.data.data
      });
    });
  },

  /**
   * 加载商品详情
   * @goodsId 商品id
   */
  loadGoodsDetails: function(options) {
    var _this = this;
    const param = {
      "goods_id": options.goodsId
    };
    wx.showLoading({
      title: '加载中',
    });
    server.postJSON("/index/goods/goods_detail", param, function(res) {
      wx.hideLoading();
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      wx.setNavigationBarTitle({
        title: res.data.data.goods_name ? res.data.data.goods_name : res.data.data.item_name
      });
      // 设置默认选择的规格
      res.data.data.defaultSpecIndex = _this.setDefaultSpecIndex(res.data.data.spec);
      // 有搭配购普通商品 设置默认选中的规格
      if (res.data.data.goods_label == 0 && res.data.data.collocation && res.data.data.collocation.length > 0) {
        for (var i = 0; i < res.data.data.collocation.length; i++) {
          res.data.data.collocation[i].defaultSpecIndex = _this.setDefaultSpecIndex(res.data.data.collocation[i].spec)
        }
      }
      for (var i = 0; i < res.data.data.spec.length; i++) {
        res.data.data.spec[i].count = 1;
      }
      if (res.data.data.goods_imgs && res.data.data.goods_imgs.length > 0) {
        res.data.data.goods_imgs = res.data.data.goods_imgs.split(",")
      }
      if (res.data.data.goods_label === 3) {
        switch (res.data.data.groupbuy_info.button_text) {
          case "众筹未开始":
            res.data.data.groupbuy_info.groupState = 10; //未开始
            _this._countLeftovertTimeDisc(res.data.data.groupbuy_info.count_down);
            break;
          case "众筹中":
            res.data.data.groupbuy_info.countDownText = _this._getCountDownText(res.data.data.groupbuy_info.count_down);
            res.data.data.groupbuy_info.groupState = 20; //进行中
            break;
          case "众筹已结束":
            res.data.data.groupbuy_info.groupState = 30; // 结束
            break;
        }
      }
      let memberAvatarList = [];
      if (res.data.data.target_quantity) {
        for (var i = 0; i < res.data.data.target_quantity; i++) {
          memberAvatarList.push("/images/default_group_avatar.svg");
        }
      }
      if (res.data.data.is_video == 2) {
        res.data.data.showVideo = true;
      } else {
        res.data.data.showVideo = false;
      }
      _this.setData({
        pageShow: true,
        memberAvatarList: memberAvatarList,
        goodsDetails: res.data.data
      });
      if (_this.data.goodsDetails.showVideo) {
        _this.videoContext = wx.createVideoContext('myVideo', _this);
        _this.videoContext.requestFullScreen();

      }
      _this.getServerData({
        ser_id: res.data.data.ser_id
      })
      _this.getShareMemberInfo(options);
      WxParse.wxParse('article', 'html', res.data.data.goods_body, _this);

    });
  },
  // 检测是否在触摸滚动
  videoMove: function(e) {
    this.videoExit();
  },
  // 视频播放结束
  videoEnd: function() {
    this.videoExit();
  },
  videoExit: function() {
    this.setData({
      "goodsDetails.showVideo": false
    })
    this.videoContext.stop();
  },
  // 检测视频是否全屏变化
  fullscreenchange(evt) {
    console.log(evt)
    if (evt.detail.fullScreen == false) {
      this.videoExit();
    }
  },
  // 获取客服信息
  getServerData: function(options) {
    const _this = this;
    server.postJSON("/index/chat/ser_info", options, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      _this.setData({
        serverData: res.data.data
      });
    })
  },
  // 设置获取默认规格下标
  setDefaultSpecIndex: function(spec) {
    var defaultSpecIndex = spec.findIndex(function(item) {
      return item.goods_storage > 0
    })
    return defaultSpecIndex
  },
  /**
   * 计算距离开始众筹剩余时间、及 说明
   */
  _countLeftovertTimeDisc(leftovertTime) {
    const _this = this;
    if (leftovertTime <= 0 ) {
      this.setData({
        "goodsDetails.groupbuy_info.groupState": 20
      })
      clearTimeout(this.data.timer);
      var goodsDetails = _this.data.goodsDetails;
      var leftovertEndTime = goodsDetails.groupbuy_info.end_time - goodsDetails.groupbuy_info.start_time
      this._getCountDownText(leftovertEndTime);
    } else {
      _this._setCountDownText(leftovertTime,'距众筹开始还有')
      leftovertTime--
      this.data.timer = setTimeout(function(){
        _this._countLeftovertTimeDisc(leftovertTime)
      },1000)
    }
  },
  // 获取倒计时时间说明
  _getCountDownText(leftovertEndTime) {
    const _this = this;
    if (leftovertEndTime <= 0) {
      clearTimeout(_this.data.timer);
      _this.setData({
        "goodsDetails.groupbuy_info.groupState": 30,
        "goodsDetails.groupbuy_info.countDownText": "众筹已结束"
      })
      return;
    } else {
      _this._setCountDownText(leftovertEndTime, '距众筹结束还有');
      leftovertEndTime--;
      _this.data.timer = setTimeout(function() {
        _this._getCountDownText(leftovertEndTime)
      },1000)
    }
    // let countDownText = "距众筹结束还有";
    // const day = Math.floor(remaining / 60 / 60 / 24) + "天";
    // const hours = Math.floor(remaining / 60 / 60 % 24) + "小时";
    // const minute = Math.floor(remaining / 60 % 60) + "分钟";
    // countDownText = countDownText + day + hours + minute;
    // _this.data.timer = setTimeout(function () {
    //   remaining--;
    //   _this.setData({
    //     "goodsDetails.groupbuy_info.countDownText": countDownText,
    //     "goodsDetails.groupbuy_info.count_down": remaining
    //   })
    //   _this._getCountDownText(remaining);
    // }, 1000);
    // return countDownText;
  },
  _setCountDownText(leftovertTime, countDownText){
    // let countDownText = "距众筹结束还有";
    const day = Math.floor(leftovertTime / 60 / 60 / 24) + "天";
    const hours = Math.floor(leftovertTime / 60 / 60 % 24) + "小时";
    const minute = Math.floor(leftovertTime / 60 % 60) + "分钟";
    const secend = leftovertTime % 60
    countDownText = countDownText + day + hours + minute + secend;
    this.setData({
      "goodsDetails.groupbuy_info.countDownText": countDownText,
      "goodsDetails.groupbuy_info.count_down": leftovertTime
    })
  },

  /**
   * 月定制添加数量
   */
  _addMonthNum(options) {
    const _this = this;
    let goodsDetails = _this.data.goodsDetails;
    let month = tool.getComponentDetail(options).month;
    let monthData = goodsDetails.serializeMonth;
    let totalCount = _this.getTotalNum();
    const storeNum = goodsDetails.spec[goodsDetails.defaultSpecIndex].goods_storage
    for (var i = 0; i < monthData.length; i++) {
      if (monthData[i].month == month) {
        monthData[i].count++;
        totalCount++;
        if (storeNum < totalCount) {
          monthData[i].count--;
          totalCount--;
          tool.warning("超出库存了");
          return;
        }
        _this.setData({
          "goodsDetails.serializeMonth": monthData
        });
      }
    }
    _this.getTotalMonthPrice();
  },
  /**
   * 月定制减少数量
   */
  _minusMonthNum(options) {
    const _this = this;
    let goodsDetails = _this.data.goodsDetails;
    let month = tool.getComponentDetail(options).month;
    let monthData = goodsDetails.serializeMonth;
    const storeNum = goodsDetails.spec[goodsDetails.defaultSpecIndex].goods_storage
    for (var i = 0; i < monthData.length; i++) {
      if (monthData[i].month == month) {
        monthData[i].count--;
        _this.setData({
          "goodsDetails.serializeMonth": monthData
        });
      }
    }
    _this.getTotalMonthPrice();
  },
  // 选择或取消 月定制月份
  _toggleMonthNum: function(options) {
    const _this = this;
    let goodsDetails = _this.data.goodsDetails;
    let month = tool.getComponentDetail(options).month;
    let monthData = goodsDetails.serializeMonth;
    const totalCount = _this.getTotalNum();
    const storeNum = goodsDetails.spec[goodsDetails.defaultSpecIndex].goods_storage
    for (var i = 0; i < monthData.length; i++) {
      if (monthData[i].month === month) {
        if (monthData[i].count > 0) {
          monthData[i].count = 0;
        } else {
          if (totalCount >= storeNum) {
            // monthData[i].count = 0;
            tool.warning("总库存只有" + storeNum);
          } else {
            monthData[i].count = 1;
          }
        }
      }
    }
    _this.setData({
      "goodsDetails.serializeMonth": monthData
    });
    _this.getTotalMonthPrice();
  },
  // 计算月定制 购买总数
  getTotalNum: function() {
    const totalNum = this.data.goodsDetails.serializeMonth.reduce(function(count, next) {
      return count += next.count;
    }, 0);
    return totalNum;
  },
  // 计算月定制 总价格
  getTotalMonthPrice: function() {
    const _this = this;
    let goodsDetails = _this.data.goodsDetails;
    const totalNum = _this.getTotalNum();
    let totalPrice = 0;
    if (totalNum == 0) {
      totalPrice = 0;
    } else {
      const selectedPrice = goodsDetails.spec[goodsDetails.defaultSpecIndex].goods_mon_price
      totalPrice = selectedPrice * totalNum
    }
    _this.setData({
      "goodsDetails.totalPrice": totalPrice
    })
  },
  // 月定制购买
  _monthCustomBuy() {
    const _this = this;
    const goodsDetails = _this.data.goodsDetails;
    const monthData = goodsDetails.serializeMonth;
    const selectMonth = monthData.filter(function(item) {
      if (item.count > 0) {
        return item;
      }
    });
    if (selectMonth.length < 3) {
      tool.warning("需满3个月起订");
      return;
    }
    // goodsDetails.serializeMonth = selectMonth;
    const param = {
      goods_id: goodsDetails.goods_id,
      serializeMonth: selectMonth,
      spec: goodsDetails.spec,
      defaultSpecIndex: goodsDetails.defaultSpecIndex,
      spec_name: goodsDetails.spec[goodsDetails.defaultSpecIndex].sp_value_name,
      goods_num: _this.getTotalNum()
    };
    let confirmOrderData = {
      chooseBuyMethod: 1,
      "from": "goodsDetails",
      "data": param,
      "totalPrice": param.goods_num * goodsDetails.spec[goodsDetails.defaultSpecIndex].goods_price
    }
    confirmOrderData = JSON.stringify(confirmOrderData);
    wx.navigateTo({
      url: '/pages/container/confirm-order-details/confirm-order-details?confirmOrderData=' + confirmOrderData,
      success: function() {
        _this.goodsParamDialog.cancelEvent();
      }
    });
  },
  /**
   * 普通商品增加选择商品的数量
   */
  _addGoodsNum: function() {
    const _this = this;
    let spec = _this.data.goodsDetails.spec;
    const specIndex = _this.data.goodsDetails.defaultSpecIndex
    const storeNum = spec[specIndex].goods_storage;
    let count = spec[specIndex].count;
    if (count < storeNum) {
      count++;
      spec[specIndex].count = count;
      _this.setData({
        "goodsDetails.spec": spec
      });
    }

  },
  /**
   *  普通商品减少选择商品的数量
   */
  _minusGoodsNum: function() {
    const _this = this;
    let spec = _this.data.goodsDetails.spec;
    const specIndex = _this.data.goodsDetails.defaultSpecIndex
    const storeNum = spec[specIndex].goods_storage;
    let count = spec[specIndex].count;
    if (count > 1) {
      count--;
      spec[specIndex].count = count;
      _this.setData({
        "goodsDetails.spec": spec
      });
    }
  },
  /**
   * 搭配购改变规格
   */
  _changeMatchSpec: function(e) {
    const _this = this;
    const matchId = e.detail.matchId;
    const matchSpecIndex = e.detail.matchSpecIndex;
    let matchIndex = 0;
    let matchGoods = {};
    for (var i = 0; i < _this.data.goodsDetails.collocation.length; i++) {
      if (_this.data.goodsDetails.collocation[i].goods_id == matchId) {
        matchGoods = _this.data.goodsDetails.collocation[i];
        matchIndex = i;
      }
    }
    const collocationStr = "goodsDetails.collocation[" + matchIndex + "].defaultSpecIndex";
    _this.setData({
      [collocationStr]: matchSpecIndex
    })

  },
  /**
   * 搭配购数量减少
   */
  _matchMinus: function(e) {
    const _this = this;
    const matchIndex = e.detail.matchIndex;
    let matchGoods = _this.data.goodsDetails.collocation[matchIndex];
    const defaultSpecIndex = matchGoods.defaultSpecIndex;
    let count = matchGoods.count ? matchGoods.count : 0;
    const countStr = "goodsDetails.collocation[" + matchIndex + "].count"
    if (count <= 0) {
      tool.warning("不能再少了。")
    } else {
      count = count - 1;
      _this.setData({
        [countStr]: count
      })
    }
  },
  /**
   * 搭配购数量增加
   */
  _matchAdd: function(e) {
    const _this = this;
    const matchIndex = e.detail.matchIndex;
    let matchGoods = _this.data.goodsDetails.collocation[matchIndex];
    const defaultSpecIndex = matchGoods.defaultSpecIndex;
    let count = matchGoods.count ? matchGoods.count : 0;
    const countStr = "goodsDetails.collocation[" + matchIndex + "].count"
    if (count < matchGoods.spec[defaultSpecIndex].goods_storage) {
      count++;
      _this.setData({
        [countStr]: count
      })
    }
  },
  // 确认选中的搭配产品
  _macthConfirm: function() {
    const _this = this;
    const matchGoods = _this.data.goodsDetails.collocation;
    const choosedMatchGoods = matchGoods.filter(function(item) {
      if (item.count && item.count > 0) {
        return item;
      }
    });
    let selectedGoodsInfo = []
    for (var i = 0; i < choosedMatchGoods.length; i++) {
      selectedGoodsInfo.push({
        goods_id: choosedMatchGoods[i].goods_id,
        sp_value_id: choosedMatchGoods[i].spec[0].sp_value_id,
        count: choosedMatchGoods[i].count,
      })
    }
    _this.chooseGeneralBuy();
    _this.setData({
      'goodsDetails.hasMatch': (selectedGoodsInfo.length > 0 ? true : false),
      "goodsDetails.selectedMatch": selectedGoodsInfo
    });
  },
  /**
   * 加入购物车
   */
  _addShoppingCart() {
    const _this = this;
    const goodsInfo = _this.data.goodsDetails;
    var specIndex = goodsInfo.defaultSpecIndex;
    let param = {};
    if (goodsInfo.goods_label == 0) {
      param = {
        member_id: app.globalData.userInfo.member_id,
        collocation: "collocation",
        collocation_info: [{
          goods_id: goodsInfo.goods_id,
          num: goodsInfo.spec[goodsInfo.defaultSpecIndex].count,
          sp_value_id: goodsInfo.spec[specIndex].sp_value_id,
          is_collocation: 1
        }]
      };
      for (var i = 0; i < goodsInfo.collocation.length; i++) {
        var collocation = goodsInfo.collocation[i];
        var collocationSpecIndex = collocation.defaultSpecIndex;
        if (collocation.count && collocation.count > 0) {
          param.collocation_info.push({
            goods_id: collocation.goods_id,
            num: collocation.count,
            sp_value_id: collocation.spec[collocationSpecIndex].sp_value_id,
            is_collocation: 2
          })
        }
      }
      param.collocation_info = JSON.stringify(param.collocation_info);
    } else {
      param = {
        member_id: app.globalData.userInfo.member_id,
        goods_id: goodsInfo.goods_id,
        sp_value_id: goodsInfo.spec[specIndex].sp_value_id,
        goods_num: goodsInfo.spec[goodsInfo.defaultSpecIndex].count
      }
    }

    server.postJSON("/index/cart/cart_add", param, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      tool.success("成功加入购物车");
    })
  },

  // 获取用户信息
  onGetUserInfo: function(res) {
    const _this = this;
    if (res.detail.errMsg == "getUserInfo:ok") {
      const nextHandle = tool.getDataset(res).handleName;
      const member_avatar = res.detail.userInfo.avatarUrl;
      const param = {
        member_id: app.globalData.userInfo.member_id,
        member_avatar: member_avatar
      }
      server.postJSON("/index/user/saveMember", param, function(res) {
        if (res.data.error != 0) {
          tool.warning(res.data.message);
          return;
        }
        if (nextHandle === "chooseGroupBuy") {
          _this.chooseGroupBuy();
        }
        _this.setData({
          isAuthSet: true
        });
      });
    } else {
      tool.warning("需要您的信息，用于展示给您的好友")
    }
  },
  //选择普通商品买法
  chooseGeneralBuy: function() {
    this.setData({
      chooseBuyMethod: 0,
      optionModelName: "general_modal"
    });
    this.showSelectSpec();
  },
  /**
   * 选择月定制买法
   */
  chooseMonthBuy: function() {
    this.setData({
      chooseBuyMethod: 1,
      optionModelName: "month_custom"

    })
    this.showSelectSpec();
    this._getSerializeMonth()
  },
  // 选择拼团买法
  chooseGroupBuy: function() {
    this.setData({
      chooseBuyMethod: 2,
      optionModelName: "group_booking"
    })
    this.showSelectSpec();
  },
  // 选择众筹买法
  chooseCrowdBuy: function() {
    this.setData({
      chooseBuyMethod: 3,
      optionModelName: "crowd_funding"
    });
    this.showSelectSpec();

  },
  // 选择月份
  _showChooseMonth: function() {
    this.setData({
      optionModelName: "month_select"
    });
    this.showSelectSpec();
  },
  // 选择搭配购买
  _chooseMatchBuy: function() {
    this.setData({
      optionModelName: "match_buy_modal"
    });
    this.showSelectSpec();
  },
  /**
   * 弹窗选择规格
   */
  showSelectSpec: function() {
    const _this = this;
    // 判断众筹商品 是否正在进行中
    if (_this.data.goodsDetails.goods_label == 3) {
      if (this.data.goodsDetails.groupbuy_info.groupState == 10) {
        tool.warning('活动还未开始');
        return
      } else if (this.data.goodsDetails.groupbuy_info.groupState == 30) {
        tool.warning("活动已结束");
        return
      }
    }
    // 判断库存是否充足
    if (_this.data.goodsDetails.goods_state == 0 || _this.data.goodsDetails.goods_storage == 0) {
      tool.warning('商品已下架或库存不足');
      return;
    }
    // 判断是否已经绑定手机
    if (!app.isMember(_this.data.userInfo)) {
      _this.setData({
        showLoginType: 'showSelectSpec'
      });
      _this.loginView.showModel();
      return;
    }
    _this._setSelectedPrice();
    _this.goodsParamDialog.showDialog();
  },
  /**
   * 立即定制
   */
  _buyGoodsHandle: function() {
    const _this = this;
    const goodsInfo = _this.data.goodsDetails;
    const selectedSpec = goodsInfo.spec[goodsInfo.defaultSpecIndex];
    let goodsArr = [{
      goods_id: goodsInfo.goods_id,
      goods_name: goodsInfo.goods_name,
      goods_image: goodsInfo.goods_image,
      num: selectedSpec.count,
      spec_name: selectedSpec.sp_value_name,
      sp_value_id: selectedSpec.sp_value_id,
      goods_price: goodsInfo.selectedPrice,
      is_collocation: 1
    }];
    if (goodsInfo.collocation) {
      for (var i = 0; i < goodsInfo.collocation.length; i++) {
        var collocation = goodsInfo.collocation[i];
        if (collocation.count && collocation.count > 0) {
          goodsArr.push({
            goods_id: collocation.goods_id,
            goods_name: collocation.goods_name,
            goods_image: collocation.goods_image,
            num: collocation.count,
            spec_name: collocation.spec[collocation.defaultSpecIndex].sp_value_name,
            sp_value_id: collocation.spec[collocation.defaultSpecIndex].sp_value_id,
            goods_price: collocation.spec[collocation.defaultSpecIndex].goods_collocation_price,
            is_collocation: 2
          })
        }
      }
    }
    let confirmOrderData = {
      "chooseBuyMethod": _this.data.chooseBuyMethod,
      "from": "goodsDetails",
      "data": goodsArr,
      "totalPrice": selectedSpec.count * goodsInfo.selectedPrice
    };

    confirmOrderData = JSON.stringify(confirmOrderData);
    let pageUrl = '/pages/container/confirm-order-details/confirm-order-details?confirmOrderData=' + confirmOrderData;
    if (_this.data.shareParam && _this.data.shareParam.type == "share") {
      pageUrl = pageUrl + "&type=" + _this.data.shareParam.type + "&cantuanid=" + _this.data.shareParam.cantuanid
    }
    wx.navigateTo({
      url: pageUrl,
      success: function() {

      }
    });
  },
  // 登陆成功后 存储数据
  _loadSuccess: function(evt) {
    this.setData({
      userInfo: evt.detail.userInfo
    });
    wx.setStorage({
      key: 'userInfo',
      data: evt.detail.userInfo
    });
    app.globalData.userInfo = evt.detail.userInfo;
    if (this.data.showLoginType == 'showChat') {
      this.showChat();
    } else {
      this.showSelectSpec();
    }
  },
  /**
   * 购物车触摸移动
   */
  cartTouchmove(e) {
    common.cartTouchmove(e, this);
    return
    let iconCartPosX = e.touches[0].clientX - 25;
    let iconCartPosY = e.touches[0].clientY;
    const dev = wx.getSystemInfoSync();
    const windowW = dev.windowWidth - 50;
    const windowH = dev.windowHeight;
    const screenH = dev.screenHeight
    if (iconCartPosX >= 0 && iconCartPosX <= windowW) {
      this.setData({
        iconCartPosX: e.touches[0].clientX - 25
      });
    }
    if (iconCartPosY >= 25 && iconCartPosY <= windowH - 50) {
      this.setData({
        iconCartPosY: e.touches[0].clientY - 25
      });
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const start_time = parseInt((new Date().getTime()) / 1000 )
    this.setData({
      start_time: start_time
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    const end_time = parseInt((new Date().getTime()) / 1000)
    const param = {
      goods_id: this.data.goodsDetails.goods_id,
      member_id: this.data.userInfo.member_id,
      start_time: this.data.start_time,
      end_time: end_time
    }
    server.postJSON("/index/goods/goods_browse",param)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    const end_time = parseInt((new Date().getTime()) / 1000)
    const param = {
      goods_id: this.data.goodsDetails.goods_id,
      member_id: this.data.userInfo.member_id,
      start_time: this.data.start_time,
      end_time: end_time
    }
    server.postJSON("/index/goods/goods_browse", param, function (res) {
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    // 右上角分享 res.from == "menu"
    // 页面内转发按钮
    const _this = this;
    const goodsDetail = _this.data.goodsDetails
    return {
      title: goodsDetail.goods_name,
      imageUrl: goodsDetail.share_image ? goodsDetail.share_image : goodsDetail.share_img,
      path: "/pages/container/goods-details/goods-details?goodsId=" + goodsDetail.goods_id + "&fromMemberId=" + app.globalData.userInfo.member_id,
      success: function(res) {
        console.log(res)
      }
    }
  },
  // 加载公司简介
  loadCompanyInfo: function() {
    var _this = this;
    server.postJSON("/index/index/footer", function(res) {
      if (res.data.error !== 0) {
        tool.warning(res.data.message);
        return;
      }
      _this.setData({
        companyInfo: res.data.data[0]
      })
    })
  }
})